var express = require('express')
var router = express.Router()
const Vote = require('../models/vote')
const Option = require('../models/option')
const Ballot = require('../models/ballot')
const sequelize = require('sequelize')
const Op = require('sequelize').Op
const Tool = require('../libs/tool')
const { check, validationResult } = require('express-validator/check')
const Interceptor = require('../libs/interceptor')
const config = require('../config/config')

/* GET votes listing. */
router.get('/', async function(req, res, next) {
  let whereObj = {}
  if (req.query.voteName) {
    whereObj['vote_name'] = {
      [Op.like]: '%' + req.query.voteName + '%'
    }
  }
  let orderObj = []
  if (req.query.order && req.query.sortby) {
    orderObj.push([req.query.sortby, req.query.order])
  }
  let interceptor = new Interceptor(req)
  let { offset = 1, limit = 10 } = interceptor.page()
  let result = await Vote.findAndCountAll({
    raw: true,
    where: whereObj,
    order: orderObj,
    offset: offset,
    limit: limit
  })
  for (let idata = 0; idata < result.rows.length; idata++) {}
  return res.json({
    code: 0,
    msg: '',
    items: result.rows,
    total: result.count
  })
})

router.get('/:voteId(\\d+)/options', [check('voteId').not().isEmpty().withMessage('投票ID不能为空')], async function(
  req,
  res,
  next
) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  let options = await Option.findAll({
    raw: true,
    where: [{ vote_id: req.params.voteId }]
  })
  return res.json({
    code: 0,
    msg: '',
    options: options
  })
})

router.get('/:voteId(\\d+)/pie', async function(req, res, next) {
  let ballots = await Ballot.findAll({
    attributes: ['option.option_name', [sequelize.fn('COUNT', sequelize.col('*')), 'ballotCount']],
    group: 'option_name',
    include: [
      {
        attributes: [['vote_id', 'voteId'], ['option_name', 'optionName']],
        association: Ballot.belongsTo(Option, { foreignKey: 'optionId' })
      }
    ],
    raw: true,
    where: { '$option.vote_id$': req.params.voteId }
  })
  let opinion = []
  let opinionData = []
  for (let i = 0; i < ballots.length; i++) {
    opinion.push(ballots[i].option_name)
    opinionData.push({ value: ballots[i].ballotCount, name: ballots[i].option_name })
  }
  return res.json({
    code: 0,
    msg: '',
    opinion: opinion,
    opinionData: opinionData
  })
})

router.get('/menus', async function(req, res, next) {
  return res.json({
    code: 0,
    msg: ''
  })
})

let dbValidator = [
  check('voteName').not().isEmpty().withMessage('投票名不能为空')
]
let createValidator = Object.assign([], dbValidator)
router.post('/', createValidator, async function(req, res) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  console.log(req.body)

  try {
    let vote = await Vote.create({
      voteName: req.body.voteName,
      description: req.body.description,
      isFinished: req.body.isFinished,
      bgnDate: req.body.bgnDate,
      endDate: req.body.endDate,
      status: req.body.status,
      createdAt: Date.now(),
      updatedAt: Date.now()
    })
    return res.json({
      code: 0,
      msg: '',
      vote: vote
    })
  } catch (err) {
    let exceptionObj = Tool.exceptionError(err)
    return res.status(exceptionObj.code).json(exceptionObj)
  }
})

let updateValidator = Object.assign([], dbValidator)
updateValidator.push(check('voteId').not().isEmpty().withMessage('投票ID不能为空'))
router.put('/:voteId', updateValidator, async function(req, res) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  let vote = await Vote.findByPk(req.params.voteId)
  if (!vote) {
    return res.status(404).json({
      code: 404,
      msg: '未找到该数据'
    })
  }
  try {
    let updateData = {
      voteName: req.body.voteName,
      description: req.body.description,
      isFinished: req.body.isFinished,
      bgnDate: req.body.bgnDate,
      endDate: req.body.endDate,
      status: req.body.status,
      updatedAt: Date.now()
    }
    let affectedRows = await vote.update(updateData, {
      where: {
        voteId: req.params.voteId
      }
    })
    return res.json({
      code: 0,
      msg: '',
      affectedRows: affectedRows[0]
    })
  } catch (err) {
    let exceptionObj = Tool.exceptionError(err)
    return res.status(exceptionObj.code).json(exceptionObj)
  }
})

let deleteValidator = [check('voteIds').not().isEmpty().withMessage('投票ID不能为空')]
router.delete('/:voteIds', deleteValidator, async function(req, res) {
  const errors = validationResult(req)
  if (!errors.isEmpty()) {
    let errObj = Tool.validatorError(errors)
    return res.status(errObj.code).json(errObj)
  }
  let voteIds = req.params.voteIds.split(',')
  let votes = await Vote.findAndCountAll({
    where: {
      voteId: {
        [Op.in]: voteIds
      }
    }
  })
  if (votes.count !== voteIds.length) {
    return res.status(404).json({
      code: 404,
      msg: '未找到匹配的数据'
    })
  }
  let inUse = []
  if (inUse.count > 0 && inUse.rows[0]['res_count'] > 0) {
    return res.status(500).json({
      code: 500,
      msg: '投票被其它数据使用'
    })
  }
  try {
    let destroyedRows = await Vote.destroy({
      where: {
        voteId: {
          [Op.in]: voteIds
        }
      }
    })
    return res.json({
      code: 0,
      msg: '',
      destroyedRows: destroyedRows
    })
  } catch (err) {
    let exceptionObj = Tool.exceptionError(err)
    return res.status(exceptionObj.code).json(exceptionObj)
  }
})

module.exports = router
